document.addEventListener('DOMContentLoaded', () => {
    const chatContainer = document.getElementById('chat-container');
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-button');
    const charCount = document.getElementById('char-count');
    const GENERATE_QUESTION_URL = '/ai/generateInterview'; // 对应后端接口路径

    marked.setOptions({
        highlight: function(code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                return hljs.highlight(code, { language: lang }).value;
            }
            return hljs.highlightAuto(code).value;
        },
        breaks: true,
        gfm: true
    });

    userInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight > 100 ? 100 : this.scrollHeight) + 'px';
        charCount.textContent = this.value.length;
        sendButton.disabled = this.value.trim().length === 0;
    });

    function sendMessage() {
        const message = userInput.value.trim();
        if (!message) return;

        const isGenerateCommand = message.toLowerCase() === '我的专属面试题';
        appendMessage('user', message);
        userInput.value = '';
        userInput.style.height = 'auto';
        charCount.textContent = '0';
        sendButton.disabled = true;

        if (isGenerateCommand) {
            handleGenerateInterview();
        } else {
            const aiTyping = appendMessage('ai', '<div class="typing-indicator"><span></span><span></span><span></span></div>');
            streamChatResponse(message)
                .then(() => chatContainer.removeChild(aiTyping))
                .catch(error => {
                    chatContainer.removeChild(aiTyping);
                    appendMessage('ai', `抱歉，发生了错误：${error.message}`);
                });
        }
    }

    async function handleGenerateInterview() {
        const loadingMessage = appendMessage('ai', '正在为你生成专属面试题，请稍候...');
        sendButton.disabled = true; // 防止重复提交

        try {
            const response = await fetch(GENERATE_QUESTION_URL, {
                method: 'GET',
                credentials: 'include', // 携带Cookie
                headers: {
                    'Content-Type': 'application/json',
                    // 可添加其他请求头
                }
            });

            if (!response.ok) {
                if (response.code === 401) {
                    throw new Error('请先登录！');
                }
                throw new Error(`请求失败：状态码 ${response.code}`);
            }

            const result = await response.json();
            appendMessage('ai', result.data || '你的面试题已生成，请前往题库查看！');

            // 生成成功后跳转（可选）
            // setTimeout(() => window.location.href = '/question-bank', 1500);

        } catch (error) {
            appendMessage('ai', `生成面试题失败：${error.message}`);
            console.error('Generate error:', error);
        } finally {
            chatContainer.removeChild(loadingMessage);
            sendButton.disabled = false;
        }
    }

    async function streamChatResponse(prompt) {
        const response = await fetch(`/ai/chat?prompt=${encodeURIComponent(prompt)}`, {
            method: 'GET',
            headers: {
                'Accept': 'text/html;charset=UTF-8'
            }
        });

        if (!response.ok || !response.body) {
            throw new Error(`HTTP error! status: ${response.code}`);
        }

        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex items-start mb-6';
        messageDiv.innerHTML = `
                <div class="h-8 w-8 rounded-lg flex items-center justify-center flex-shrink-0 mt-1 bg-primary text-white">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="ml-3 bg-neutral rounded-xl rounded-tl-none p-4 max-w-[90%]">
                    <div id="ai-response" class="markdown-output"></div>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;

        const responseElement = messageDiv.querySelector('#ai-response');
        let accumulatedMarkdown = '';
        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            accumulatedMarkdown += chunk;
            responseElement.innerHTML = marked.parse(accumulatedMarkdown);
            responseElement.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        return messageDiv;
    }

    function appendMessage(sender, content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex items-start mb-6';
        let iconClass, bubbleClass;

        if (sender === 'user') {
            iconClass = 'bg-gray-200 text-gray-600';
            bubbleClass = 'ml-auto bg-primary text-white rounded-xl rounded-tr-none';
        } else {
            iconClass = 'bg-primary text-white';
            bubbleClass = 'ml-3 bg-neutral rounded-xl rounded-tl-none';
        }

        if (sender === 'ai' && content.includes('<div class="typing-indicator">')) {
            messageDiv.innerHTML = `
                    <div class="h-8 w-8 rounded-lg flex items-center justify-center flex-shrink-0 mt-1 ${iconClass}">
                        <i class="fa fa-robot"></i>
                    </div>
                    <div class="${bubbleClass} p-4 max-w-[90%]">
                        <p>${content}</p>
                    </div>
                `;
        } else {
            messageDiv.innerHTML = `
                    <div class="h-8 w-8 rounded-lg flex items-center justify-center flex-shrink-0 mt-1 ${iconClass}">
                        <i class="fa fa-${sender === 'user' ? 'user' : 'robot'}"></i>
                    </div>
                    <div class="${bubbleClass} p-4 max-w-[90%]">
                        <div class="markdown-output">${marked.parse(content)}</div>
                    </div>
                `;
            messageDiv.querySelectorAll('pre code').forEach(block => hljs.highlightElement(block));
        }

        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
        return messageDiv;
    }

    sendButton.addEventListener('click', sendMessage);
    userInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
});